package com.qzdsoft.erpcloud.controller.pu;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qzdsoft.erpcloud.controller.BaseController;
import com.qzdsoft.erpcloud.domain.com.CustomerSupplierContacts;
import com.qzdsoft.erpcloud.domain.pu.PurchaseApply;
import com.qzdsoft.erpcloud.domain.sys.LoginUser;
import com.qzdsoft.erpcloud.service.com.CustomerSupplierService;
import com.qzdsoft.erpcloud.service.com.CustomerSupplierStatementService;
import com.qzdsoft.erpcloud.service.com.StaffService;
import com.qzdsoft.erpcloud.service.proj.MaterialService;
import com.qzdsoft.erpcloud.service.pu.PurchaseApplyService;
import com.qzdsoft.erpcloud.service.stock.StockStoreService;
import com.qzdsoft.erpcloud.service.sys.Permission;
import com.qzdsoft.erpcloud.vo.com.CustomerSupplierStatementInfo;
import com.qzdsoft.erpcloud.vo.com.StaffInfo;
import com.qzdsoft.erpcloud.vo.proj.MaterialInfo;
import com.qzdsoft.erpcloud.vo.proj.MaterialQueryInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseApplyDetailInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseApplyDetailQueryInfo;
import com.qzdsoft.erpcloud.vo.pu.PurchaseApplyInfo;
import com.qzdsoft.utils.ExceptionUtil;
import com.qzdsoft.vo.LayTableResponse;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;
import com.qzdsoft.vo.TypeInfo;
import com.qzdsoft.vo.proj.MaterialReviewStatus;
import com.qzdsoft.vo.pu.PurchaseOrderStatus;
/**
 * @author Create By:ZhangHao Date:2017-08-18
 * @version
 * 描述：采购申请/请购单
 */
@Controller
@RequestMapping("/pu/purchaseapply")
public class PurchaseApplyController extends BaseController{
    private static final String BASEPATH = "pu/purchaseapply";
    private static final Logger logger = LoggerFactory.getLogger(PurchaseApplyController.class);
    
    @Autowired
    private PurchaseApplyService purchaseApplyService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private CustomerSupplierStatementService customerSupplierStatementService;
    @Autowired
    private CustomerSupplierService customerSupplierService;
    @Autowired
    private MaterialService materialService;
    @Autowired
    private StockStoreService stockStoreService;
    /**
	 * @author ZhangHao
	 * Date:2017-08-28
	 * @return
	 */
    @Permission(validate=false)
	@RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView();
        List<TypeInfo> status = PurchaseOrderStatus.ALL;
        mv.addObject("status",status);
        mv.setViewName(BASEPATH+"/index");
        return mv;
    }
	
	/**
     * 首页单据网格（表头）
     * @param request
     * @param response
     * @return
     * @throws Exception 
     */
    @ResponseBody
    @RequestMapping("/data")
    public LayTableResponse<PurchaseApplyInfo> list(int page,int limit) throws Exception {
        //layui table  网格数据源 
        LayTableResponse<PurchaseApplyInfo> tabledata = purchaseApplyService.getHeaderData(page,limit);
    	return tabledata;
    }
    
    /**
   	 * 打开请购单表头新增页面
   	 * 
   	 * @param model
   	 * @param request
   	 * @return
   	 */
    @Permission(validate=false)
    @RequestMapping("/headeradd")
    public ModelAndView detail(int companyid,Integer id) {
        ModelAndView mv = new ModelAndView();
        List<StaffInfo> staffList = staffService.getAllStaff(companyid);
        
        //请购人信息
        mv.addObject("staffIds", staffList);
        mv.addObject("companyId", getUser().getCompanyId());
        List<TypeInfo> status = PurchaseOrderStatus.ALL;
        mv.addObject("status",status);
        mv.setViewName(BASEPATH+"/add");
        return mv;
    }
    
    /**
     * 打开请购单表头修改页面
     * @param model
     * @param request
     * @return
     * @throws Exception 
     */
    @Permission(validate=false)
    @RequestMapping("/headeredit")
    public ModelAndView showeditinfo(int companyid,Integer id) throws Exception {
        ModelAndView mv = new ModelAndView();
        PurchaseApplyInfo currentRecord = purchaseApplyService.findById(companyid,id);
        mv.addObject("order", currentRecord);
        //加载供应商联系人
        List<CustomerSupplierContacts> contacts = customerSupplierService.selectAll(currentRecord.getSupplyId()+"");
        mv.addObject("contacts",contacts);
        
        List<StaffInfo> staffList = staffService.getAllStaff(companyid);
        //请购人信息
        mv.addObject("staffList", staffList);
        List<TypeInfo> status = PurchaseOrderStatus.ALL;
        mv.addObject("status",status);
        mv.setViewName(BASEPATH+"/edit");
        return mv;
    }
    
    /**
     * 请购单表头 新增
     * @param apply
     * @return
     * @throws Exception 
     */
    @ResponseBody
    @RequestMapping("/add")
    public Response<String> add(PurchaseApply apply) throws Exception{
        logger.debug("请购单:{}",apply);
        try {
            return  purchaseApplyService.add(apply);
        }catch(Exception ex) {
            logger.error("新增采购订单错误，异常信息：{}",ExceptionUtil.getStackTrace(ex));
        }
        return new Response<>(ResultEnum.ERROR);
    }
    
    /**
     * 采购订单表头 新增
     * @param apply
     * @return
     * @throws Exception 
     */
    @ResponseBody
    @RequestMapping("/edit")
    public Response<String> edit(PurchaseApply apply) throws Exception{
        return purchaseApplyService.edit(apply);
    }
    
    /**
     * 采购订单表头 新增
     * @param apply
     * @return
     * @throws Exception 
     */
    @ResponseBody
    @RequestMapping("/headerdel")
    public Response<String> headerdel(PurchaseApply apply) throws Exception{
        return purchaseApplyService.headerdel(apply);
    }
    
    /**
     * 请购单审核
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/review")
    public Response<String> review(Integer id) {
        logger.debug("采购申请单审核:id={}",id);
        Response<String> aa =purchaseApplyService.review(id);
        return aa;
    }
    
    /**
     * 请购单弃审
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/cancleReview")
    public Response<String> cancleReview(Integer id) {
        logger.debug("采购申请单弃审:id={}",id);
        return purchaseApplyService.cancleReview(id);
    }
    
    /**
     * 供应商结算方式查询
     * @param supplierid
     * @return
     */
    @Permission(validate=false)
    @ResponseBody
    @RequestMapping("/querySettleMethod/{supplierid}")
    public CustomerSupplierStatementInfo querySettleMethod(@PathVariable("supplierid")Integer supplierid) {
        //供应商结算方式
       LoginUser user = getUser();
       Integer companyid = user.getCompanyId();
       List<CustomerSupplierStatementInfo> list = customerSupplierStatementService.selectBy(companyid, supplierid);
       if(list.size()>0){
           return list.get(0);    
       }else
        return null;
    }
    
    /**
     * 供应商税率信息查询
     * @param supplierid
     * @return
     */
    @Permission(validate=false)
    @ResponseBody
    @RequestMapping("/queryTax/{supplierid}/{companyid}")
    public TypeInfo queryTax(@PathVariable("supplierid")Integer supplierid,@PathVariable("companyid")Integer companyid) {
        return customerSupplierService.selectTaxInfo(companyid, supplierid);
        
    }
    /**
     * 明细页面跳转
     * @param id
     * @return
     * @throws Exception
     */
    @Permission(validate=false)
    @RequestMapping("/detail")
    public ModelAndView index(Integer id) throws Exception {
        //查询请购单
        PurchaseApplyInfo currentRecord = purchaseApplyService.findById(getUser().getCompanyId(),id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("order",currentRecord);
        mv.setViewName(BASEPATH + "/detail");
        return mv;
    }
    
    /**
     * 跳转到页面
     * @return
     * @throws Exception 
     */
    @RequestMapping("/order-details")
    public ModelAndView item(Integer id,PurchaseApplyDetailQueryInfo queryinfo) throws Exception
    {
        //查询物料信息
        MaterialQueryInfo info = new MaterialQueryInfo();
        info.setIsBuy(true);//采购的物料
        info.setStatus(MaterialReviewStatus.HAS_REVIEW_CODE);//查询已经审核的物料
        List<MaterialInfo> materialInfos = materialService.selectBy(info);
        ModelAndView mv = new ModelAndView();
        mv.addObject("materials", materialInfos);
       
        //查询采购订单
        PurchaseApplyInfo currentRecord = purchaseApplyService.findById(queryinfo.getCompanyId(),id);
        mv.addObject("order",currentRecord);
        
//        Integer companyid = purchaseOrderInfo.getCompanyid();
//        Integer supplierid= purchaseOrderInfo.getSupplierid();
        
//        //供应商结算方式
//        List<CustomerSupplierStatementInfo> customerSupplierStatements = customerSupplierStatementService.selectBy(companyid, supplierid);
//        mv.addObject("statements",customerSupplierStatements);
        
        //明细列表
        List<PurchaseApplyDetailInfo> list = purchaseApplyService.selectDetailByBillId(queryinfo);
        mv.addObject("details",list);
        
        //仓库列表
        List<TypeInfo> stores = stockStoreService.selectStockStore(queryinfo.getCompanyId());
        mv.addObject("stores",stores);
        
        mv.setViewName(BASEPATH + "/detailItem");
        return mv;
    }
    
	/**
	 * 创建请购单 明细信息
	 * @param childbom
	 * @param request
	 * @return
	 * @throws Exception
	 */
//	@ResponseBody
//	@RequestMapping(value = "/addChildBom", method = RequestMethod.POST)
//	public Response addChildBom(@ModelAttribute TProjBomItem childbom, HttpServletRequest request)
//			throws Exception {
//		User loginUser = sessionService.getLoginInfo(request);
//		// 提交保存
//		return bomService.addChildBom(childbom, loginUser);
//	}
}
